/*
This file is part of Socks via HTTP.

This package is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

Socks via HTTP is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Socks via HTTP; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

// Title :        DiskAccess.java
// Version :      1.0
// Copyright :    Copyright (c) 2001-2002
// Author :       Florent CUETO  & Sebastien LEBRETON <socksviahttp@cqs.dyndns.org>
// Description :  Disk Access (writing)

package socksviahttp.core.log;

import java.io.*;

// Multithreaded file writer
public class DiskAccess extends Thread
{
  // Members
  private String fileName = null; // Filename
  private byte[] toWrite = null;  // bytes to write

  // Constructor
  public DiskAccess(String fileName, byte[] toWrite)
  {
    this.fileName = fileName;
    this.toWrite = toWrite;
  }

  public void run()
  {
    //
    boolean success = false;
    int cpt = 0;

    // Try to write the file
    // Stop condition:
    // 1 - Write successful
    // 2 - Max number of retries over
    while((!success) && (cpt < 6))
    {
      try
      {
        FileOutputStream fos = new FileOutputStream(fileName, true);

        // Write the bytes
        fos.write(toWrite);

        // Flush the file
        fos.flush();

        // Close the file
        fos.close();
        fos = null;

        // Operation OK
        success = true;
      }
      catch(IOException e)
      {
        // Sleep for a while
        // and retry
        try
        {
          this.sleep(500);
        }
        catch(InterruptedException ex){}
        cpt++;
      }
    }
  }
}
